package zcatt.ex004.ui.view;

import java.util.Map;

import org.eclipse.core.runtime.Assert;
import org.eclipse.e4.core.contexts.IEclipseContext;
import org.eclipse.e4.core.internal.contexts.EclipseContext;
import org.eclipse.e4.core.contexts.EclipseContextFactory;
import org.eclipse.e4.ui.internal.workbench.E4Workbench;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.osgi.framework.BundleContext;

public class MyView extends ViewPart {
	public static final String ID="zcatt.ex004.ui.view.myview";
	
	Text text;
	
	public MyView() {
		super();
	}

	void logEclipseContext(EclipseContext ec)
	{
		Assert.isNotNull(ec);
		
		int level = 0;
		while(ec != null)
		{
			text.append("\n================================================\n");
			text.append("\neclipseContext("+ level-- +"): " + ec + " ..............\n");
			
			text.append("\nlocal data:          \n");
			Map<String, Object> map = ec.localData();
			for(Map.Entry<String, Object> e : map.entrySet())
			{
				text.append(e.getKey() + ",\t\t\t"+ e.getValue() + "\n");				
			}		
			
			text.append("\nlocal context functions:          \n");
			map = ec.localContextFunction();
			for(Map.Entry<String, Object> e : map.entrySet())
			{
				text.append(e.getKey() + ",\t\t\t"+ e.getValue() + "\n");				
			}		

			ec = ec.getParent();
		}		
	}
	
	@Override
	public void createPartControl(Composite parent) {
		text = new Text(parent, SWT.BORDER|SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
		text.setText("zcatt.ex004.ui.view");

		IEclipseContext iec = null;
		
//		try {
//			iec = E4Workbench.getServiceContext();	//zf, error?
//		}
//		catch(Exception e)
//		{
//			e.printStackTrace();
//		}
//		
		//create one EclipseContextOSGi
//		BundleContext bundleCtx = Activator.bundleCtx;
//		iec = EclipseContextFactory.getServiceContext(bundleCtx);
		
		//get the workbench EclipseContext
//		IWorkbenchWindow ww = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
//		Assert.isNotNull(ww);		
//		iec = ww.getService(IEclipseContext.class);
		
		//get the view part EclipseContext
		iec = getSite().getService(IEclipseContext.class);

		EclipseContext ec = (EclipseContext) iec;
		logEclipseContext(ec);
		
		text.append("\n\n\n");
		BundleContext bundleCtx = Activator.bundleCtx;
		iec = EclipseContextFactory.getServiceContext(bundleCtx);	//zf, 此调用创建的是新的与该bundleCtx关联的EclipseContextOSGi.
		ec = (EclipseContext) iec;
		logEclipseContext(ec);
	}

	@Override
	public void setFocus() {
		if(text != null)
		{
			text.setFocus();
		}
	}

}
